package org.zhaozhen.basic.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.zhaozhen.basic.businessexception.BusinessException;
import org.zhaozhen.basic.service.IVerifyCodeService;
import org.zhaozhen.basic.util.SmsUtils;
import org.zhaozhen.basic.util.StrUtils;
import org.zhaozhen.user.mapper.UserMapper;

import java.util.Map;
import java.util.concurrent.TimeUnit;


public class VerifyCodeServiceTest implements IVerifyCodeService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public void sendSmsCode(String phone) {
        try {
            //先判断手机号是否为空
            if (StringUtils.isEmpty(phone)){
                throw new BusinessException("手机号不能为空");
            }
            //判断用户是否已经注册
            if (userMapper.loadByPhone(phone)!=null){
                throw new BusinessException("该用户已经注册");
            }
           //定义key
            String key =  "verifycode_register:"+phone;
            //从Redis中获取key
            Object value = redisTemplate.opsForValue().get("key");
            //判断获取的value是否为空
            String code="";
            if (value!=null){
                //先截取value
                Long oldTime = Long.valueOf(value.toString().split("1")[1]);
                //判断是否过了重发时间
                if ((System.currentTimeMillis()-oldTime)<=1*60*1000){
                    throw new BusinessException("请勿重复获取验证码");
                }else {
                   code= value.toString().split("1")[0];

                }
            }else {
                code = StrUtils.getComplexRandomString(6);
            }
            //将key和value保存到Redis
            String codeValue=code+":"+System.currentTimeMillis();
            redisTemplate.opsForValue().set(key, codeValue, 3, TimeUnit.MINUTES);
            SmsUtils.sendSms(phone, "你的验证码是："+code+"，三分钟内使用");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void sendSmsCode(Map<String, String> obj) {

    }
}
